package com.simin.base.appnet;

import com.simin.base.appnet.netother.HttpConstant;
import com.simin.base.sqlite.DiskCacheManager;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.Proxy;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by wsm on 2016/5/7.
 */
public class NetWork {

    public NetWork() {

    }


    /**
     * HttpLoggingInterceptor 是一个okhttp拦截器，输出网络请求和结果的 Log
     * 它有三种模式 BASIC / HEADERS / BODY  基础，头，身体
     * MarvelSigningInterceptor 也是一个okhttp拦截器 ，用于密钥使用的
     * ---Okhttpclient 的创建时通过Builder的build（）方法创建的，其中的参数，都是设置配置
     */

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()

            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))//添加一个拦截器
//                    .addNetworkInterceptor(mTokenInterceptor) //让所有网络请求都附上你的拦截器
            //.connectTimeout   设置连接时间
            // .retryOnConnectionFailure   设置连接错误进行重新连接
            //.authenticator()  设置身份验证
            //.cache()  设置网络请求缓存
            //.dispatcher() 分发
            .proxy(Proxy.NO_PROXY)//代理
            // .dns()  dns
            //.authenticator()  证书
            //.proxyAuthenticator()  代理证书
            // .addInterceptor(new KeyValueXXTEAIntercepter())//各别参数加密拦截
            .addInterceptor(new Interceptor() {//添加一个拦截器，设置公用的Headers，
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("Authorization", "Bearer " + DiskCacheManager.getString("token"))
                            .build();
                    System.out.println("login token:"+"Bearer " + DiskCacheManager.getString("token"));
                    return chain.proceed(request);
                }

            })
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    /**
     * Retrofit2 使用配置 通过Builder创建
     * 它的最简单配置：
     * Retrofit retrofit = new Retrofit.Builder()
     * .baseUrl("https://api.github.com/")
     * .build();
     */
    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(HttpConstant.getBaseUrl())//  * .baseUrl  是设置连接的地址
            .client(okHttpClient)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//* .addCallAdapterFactory 添加Rxjava适配器
            .addConverterFactory(GsonConverterFactory.create())//* .addConverterFactory  添加自定义转换器
//            .addConverterFactory(GsonConverterFactory.create())//* .addConverterFactory  添加自定义转换器
            .build();

    public static <T> T createApi(Class<T> tClass) {

        return retrofit.create(tClass);

    }

    /**
     * 转json格式传给接口
     *
     * @param map
     * @return
     */
    public static RequestBody Body(Map<String, Object> map) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(map));
    }


    /**
     * description 忽略https证书验证
     */
    private static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
    /**
     * description 忽略https证书验证
     */
    private static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }

    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

}
